import SelectStationCard from "../../utils/SelectStationCard";
import {List} from "antd-mobile";
import {useState} from "react";
import BusCard from "./component/BusCard";
import {BuyTicketModal} from "./component/BuyTicketModal";
import {fetchPassengers} from "../../utils/http/PassengerController";
import {fetchTicketsInfoForNo} from "../../utils/http/TicketController";

const HomePage = ()=>{

    const [items, setItems] = useState<any>(null);

    const [noId, setNoId] = useState<any>(null);
    const [visible, setVisible] = useState<boolean>(false);
    const [passengers, setPassengers] = useState<any>(null);
    const [tickets, setTickets] = useState<any>(null);

    const showModal = async (id: any)=>{
      setNoId(id);

      if (!passengers){
          const res = await fetchPassengers()
          setPassengers(res.map((value: any)=>{
              return{
                  label: value.name,
                  value: value.id
              };
          }));
      }
      const res = await fetchTicketsInfoForNo(id);
      setTickets(res.map((value: any)=>{
            return {
                label: value.seat,
                disabled: value.status === 1,
                value: value.id
            };
      }));
      setVisible(true);
    };

    const renderBusNo = (res: [any]) => {
      const items = res.map((value: any)=>{
          return (
              <List.Item key={value.id}>
                  <BusCard {...value} onBuy={showModal}/>
              </List.Item>
          )
      });
      setItems(items);
    }


    return (
      <>
          <SelectStationCard onComplete={renderBusNo}/>

          <List style={{width: "100%", marginTop: "2rem", backgroundColor: "#f0f0f022"}}>
              {items}
              {/*<List.Item>*/}
              {/*    <BusCard {...bus} />*/}
              {/*</List.Item>*/}
          </List>

          <BuyTicketModal noId={noId} visible={visible}
                          onClose={()=>setVisible(false)}
                          passengers={passengers} tickets={tickets}/>
      </>
    );
}

export default HomePage;

